<template>
  <div class="chart-container">
    <slot></slot> <!-- 地图通常不需要标题，但保留插槽以保持一致性 -->
    <div ref="chartRef" class="chart-content"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts/core';
import { MapChart } from 'echarts/charts';
import { TooltipComponent, VisualMapComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
// 引入中国地图 JSON 数据并注册
import chinaMapData from '../../public/json/china.json';

echarts.use([TooltipComponent, VisualMapComponent, MapChart, CanvasRenderer]);
// 注册中国地图
echarts.registerMap('china', chinaMapData);

const chartRef = ref(null);
let chartInstance = null;

const option = ref({ // 地图 Option (Copied from Home.vue)
  tooltip: {
    trigger: 'item', formatter: '{b} : {c}',
    backgroundColor: 'rgba(0, 10, 30, 0.8)', borderColor: '#0ff', textStyle: { color: '#fff' }
   },
  visualMap: {
    min: 0, max: 100, left: '5%', bottom: '5%', text: ['高', '低'], calculable: true,
    inRange: { color: ['#0B3B80', '#1E90FF', '#00FFFF', '#7FFFD4'] },
    textStyle: { color: 'rgba(204, 238, 255, 0.8)' }
  },
  geo: {
        map: 'china', roam: true, zoom: 1.2,
        itemStyle: {
            areaColor: 'rgba(10, 23, 62, 0.6)', borderColor: 'rgba(0, 198, 255, 0.3)',
            shadowColor: 'rgba(0, 0, 0, 0.5)', shadowBlur: 5
        },
        emphasis: {
             itemStyle: { areaColor: 'rgba(0, 198, 255, 0.3)', borderColor: '#0ff', },
             label: { color: '#fff' }
        }
    },
  series: [{
    name: '地区人数占比', type: 'map', map: 'china', roam: false, geoIndex: 0,
    label: { show: false },
     emphasis: { label: { show: true, color: '#fff' }, itemStyle: { areaColor: '#7FFFD4' } },
    data: []
  }]
});

const initChart = async () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);
  try {
    const response = await axios.get('/api/location_distribution');
     if (response.data.code === 200) {
        option.value.series[0].data = response.data.data;
        const maxVal = Math.max(...response.data.data.map(item => item.value), 100);
        option.value.visualMap.max = maxVal > 0 ? maxVal : 100;
        chartInstance.setOption(option.value, true);
     } else {
         console.error("Chart3 Error:", response.data.msg);
     }
  } catch (error) {
    console.error("Chart3 Network Error:", error);
  }
};

const resizeHandler = () => {
  chartInstance?.resize();
};

onMounted(async () => {
  await nextTick();
  initChart();
  window.addEventListener('resize', resizeHandler);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler);
  chartInstance?.dispose();
});
</script>

<style scoped>
.chart-container { width: 100%; height: 100%; display: flex; flex-direction: column; }
/* 地图通常占满容器，不需要额外的内容区域样式调整 */
.chart-content { flex-grow: 1; width: 100%; height: 100%; }
</style>